package com.lihonghao.controller.spring;

import cn.hutool.core.thread.ThreadUtil;
import com.lihonghao.handle.HttpForwardHandler;
import com.lihonghao.utils.RedisUtil;
import io.netty.channel.*;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.SocketAddress;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/send")
public class SendController {
    @Autowired
    private RedisUtil redisUtil;

    private Logger logger = LoggerFactory.getLogger(SendController.class);
    @GetMapping
    public String send() throws InterruptedException {
        Object httpForwardChannel = redisUtil.get("http_forward_channel");
        if (httpForwardChannel != null && httpForwardChannel instanceof SocketAddress) {
            SocketAddress remoteAddress = (SocketAddress) httpForwardChannel;
            CountDownLatch latch = new CountDownLatch(1);

            Channel channel = HttpForwardHandler.channelGroup.stream().map(channel1 ->
                    channel1.remoteAddress().equals(remoteAddress) ? channel1 : null).filter(Objects::nonNull).findFirst().get();


            channel.writeAndFlush("{http_forward_channel} test").addListener(future -> {
                if (future.cause() != null) {
                    logger.error("netty消息发送失败:", future.cause());
                } else if (future.isSuccess()) {
                    logger.info("netty消息发送成功至客户端 :{}", "test");
                } else {
                    logger.error("Message send failed for an unknown reason.");
                }
            });
            //同步获取future的响应值
            try {
                //latch.await(5, TimeUnit.SECONDS)
                if (ThreadUtil.sleep(5000)) {
                    String responseHolder = (String) redisUtil.get("back");
                    if (responseHolder!= null) {
                        return responseHolder;
                    } else {
                        return "未接收到服务器响应";
                    }
                } else {
                    return "等待服务器响应超时";
                }
            } catch (Exception e) {
                logger.error("等待过程被中断", e);
                Thread.currentThread().interrupt();
                return "等待过程被中断";
            }
        }
        return "error";
    }
}
